#pragma once

template<class T>
class GRefScope {
public:

  GRefScope()
  : mpOldInstance(GRef<T>::mpInstance)
  {
    GRef<T>::mpInstance = &mInstance;
  }

  ~GRefScope()
  {
    GRef<T>::mpInstance = mpOldInstance;
  }

private:
  T   mInstance;
  T * mpOldInstance;
};

template <class T>
class GRef {
  friend class GRefScope<T>;

public:

  operator T*()
  {
    return mpInstance;
  }

  operator T&()
  {
    return *mpInstance;
  }

  T * operator->()
  {
    return mpInstance;
  }

private:
  static T * mpInstance;
};

template<class T>
T * GRef<T>::mpInstance = 0;